
/**
 * 检验参数中间件
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
const $ = require('../utils/common')
const configs = require('../config')

const check_parameter = function (req, res, next) {
    
    var par
    if (req.method == 'GET') {
        par = JSON.parse(JSON.stringify(req.query))
        delete par.token
    }
    else if (req.method == 'POST') {
        par = JSON.parse(JSON.stringify(req.body))
        delete par.token
    }
    // 防止多次打印
    if (req.user_name) {
        $.log('URL : ', req._parsedUrl.pathname)
        $.log('USER :', req.user_name)
        $.log('PAR : ', par)
    }

    // 有user_id
    const has_user_id = configs.has_user_id
    if (has_user_id.includes(req._parsedUrl.pathname)) {
        // $.log('检查 user_id', req._parsedUrl.pathname)
        // get method check user_id 
        if (req.method == 'GET') {
            if ($.isEmpty(req.query.id)) {
                $.sendMessage(res, 1016, 'id 不存在')
                return
            }
            next()
            return
        }
        if (req.method == 'POST') {
            if ($.isEmpty(req.body.id)) {
                $.sendMessage(res, 1016, 'id 不存在')
                return
            }
            next()
            return
        }
        $.sendMessage(res, 1016, 'please send get or post method')
        return
    }


    // 有size 和 page
    const page_and_size = configs.has_page_and_size_parameter_urls
    if (page_and_size.includes(req._parsedUrl.pathname)) {
        // $.log('检查size 和 page', req._parsedUrl.pathname)
        // 是否为空
        if ($.isEmpty(req.query.size) || $.isEmpty(req.query.page)) {
            $.sendMessage(res, 1016, 'page or size1 参数不存在')
            return
        }
        // 是否为正整数
        if (!$.isValuablePage(req.query.page)) {
            $.sendMessage(res, 1016, 'page 格式有误')
            return
        }
        if (!$.isValuableSize(req.query.size)) {
            $.sendMessage(res, 1016, 'size 格式有误')
            return
        }
        next()
        return
    }
    next()
}

module.exports = check_parameter